package com.apes.scm.masterdata.enumeration.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.Tag;
import com.apes.scm.masterdata.enumeration.repository.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by lishikun on 2021/1/25 17:33
 */
@Service("tagService")
public class TagService extends DomainService {

    @Autowired
    TagRepository tagRepository;

    public Tag save(SimpleRequest request){
        Tag tag = request.getO(Tag.class);
        return tagRepository.saveAndFlush(tag);
    }
    public Tag update(SimpleRequest request) {
        Tag tag = request.getO(Tag.class);
        return tagRepository.saveAndFlush(tag);
    }
    public Page<Tag> findAll(SimpleRequest request) {
        Group group = findAllCore(request);
        return tagRepository.findAll(group.build(true), JpaDsl.getPageable(request));
    }
    public String delete(SimpleRequest request) {
        Tag tag = request.getO(Tag.class);
        tagRepository.delete(tag);
        return "删除成功";
    }



    /***
     * 抽取的公共逻辑
     */
    private Group findAllCore(SimpleRequest request) {
        Group group = JpaDsl.getGroup(request);

        List<Filter> filters = group.getFilters();
        // 找到id参数
        Filter filter = filters.stream().filter( item -> item.getField().equals("id")).findFirst().orElse(null);
        if( filter != null ) {
            filters.remove(filter); // 移除当前id查询参数,换成id和name的模糊查询条件
            group.addGroup(createIdGroup(filter));
        }
        filter = filters.stream().filter( item -> item.getField().equals("baseTag")).findFirst().orElse(null);
        if( filter != null && (Integer) filter.value != 1) {
            filters.remove(filter); // 移除当前id查询参数,换成id和name的模糊查询条件
        }
        filter = filters.stream().filter( item -> item.getField().equals("valid")).findFirst().orElse(null);
        if( filter != null && (Integer) filter.value != 1) {
            filters.remove(filter); // 移除当前id查询参数,换成id和name的模糊查询条件
        }
        return group;
    }


    /***
     * 构建订单 Group
     */
    private Group createIdGroup(Filter filter) {
        Group idGroup = new Group();
        idGroup.setOperator("or");
        idGroup.addFilters(
                JpaDsl.toFilter(
                        "id","like", filter.getValue(),
                        "name", "like", filter.getValue()
                )
        );
        return idGroup;
    }
}
